<template>
  <div>
    <el-dialog
      :title="action == 'invoice' ? '发票索取' : '申请合同'"
      v-model="dialogVisible"
      width="60%"
      @close="closeDialog"
    >
      <div>
        <div class="query">
          <el-form ref="queryParamsRef" inline :model="queryParams" label-width="90px">
            <el-form-item label="订单编号" props="sn">
              <el-input v-model="queryParams.sn" placeholder="输入订单编号" clearable />
            </el-form-item>
            <el-form-item label="订单类型" props="shoppingCarEnums">
              <el-select
                v-model="queryParams.shoppingCarEnums"
                placeholder="请选择订单类型"
              >
                <el-option
                  v-for="item in typeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="querySearch"> 查询 </el-button>
              <el-button type="primary" plain @click="resetQuery">重置 </el-button>
            </el-form-item>
          </el-form>
          <div style="flex: 1">
            <el-button
              type="primary"
              style="float: right"
              @click="onSubmit()"
              :disabled="multipleSelection.length == 0"
            >
              立即申请
            </el-button>
          </div>
        </div>
        <el-table
          :data="orderList"
          border
          header-cell-class-name="title-style"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="55"
            :selectable="selectable"
            align="center"
          />
          <el-table-column prop="sn" label="订单编号" align="center" width="200" />
          <el-table-column prop="carEnums" label="订单类型" width="180" align="center">
            <template #default="scope">
              {{ getEnumsLabel(scope.row.shoppingCarEnums) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="updatePrice"
            label="金额(元)"
            width="150"
            align="center"
          />
          <el-table-column prop="orderAbstract" label="订单摘要" align="center" />
          <el-table-column prop="invoicing" label="状态" align="center">
            <template #default="scope">
              <el-tag
                v-if="action == 'invoice'"
                :type="scope.row.invoicing == 1 ? 'warning' : 'success'"
              >
                {{ scope.row.invoicing == 1 ? "开票中" : "未开票" }}
              </el-tag>
              <el-tag
                v-if="action == 'contract'"
                :type="scope.row.contractStatus == 1 ? 'warning' : 'success'"
              >
                {{ scope.row.contractStatus == 1 ? "申请中" : "可申请" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="120">
            <template #default="scope">
              <el-button
                link
                type="primary"
                v-if="action == 'invoice' && scope.row.invoicing == 0"
                @click="onSubmit(scope.row)"
              >
                申请
              </el-button>
              <el-button
                link
                type="primary"
                v-if="action == 'contract' && scope.row.contractStatus == 0"
                @click="onSubmit(scope.row)"
              >
                申请
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="page-footer">
          <el-pagination
            :total="total"
            v-model:current-page="queryParams.params.pageNum"
            v-model:page-size="queryParams.params.pageSize"
            layout="total, prev, pager, next"
            small
            @size-change="getOrderList"
            @current-change="getOrderList"
          />
        </div>
      </div>
    </el-dialog>

    <el-dialog v-model="invoiceShow" title="发票申请" width="600px">
      <el-form
        label-position="left"
        label-width="180px"
        ref="invoiceRef"
        :rules="invoiceRules"
        :model="invoiceForm"
      >
        <el-form-item label="发票类型" prop="invoiceType">
          <el-radio-group v-model="invoiceForm.invoiceType">
            <el-radio :label="1">增值税普通发票</el-radio>
            <el-radio :label="2">增值税专用发票</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发票抬头（公司名称）" prop="invoiceTittle">
          <el-input v-model="invoiceForm.invoiceTittle" placeholder="请填写抬头" />
        </el-form-item>
        <el-form-item label="纳税人识别号" prop="taxpayerId">
          <el-input v-model="invoiceForm.taxpayerId" placeholder="请填写纳税人识别号" />
        </el-form-item>
        <el-form-item label="收件人姓名" prop="recipientName">
          <el-input v-model="invoiceForm.recipientName" placeholder="请填写收件人姓名" />
        </el-form-item>
        <el-form-item label="收件人地址" prop="recipientAddress">
          <el-input
            v-model="invoiceForm.recipientAddress"
            placeholder="请填写收件人地址"
          />
        </el-form-item>
        <el-form-item label="邮政编码" prop="zipCode">
          <el-input
            v-model="invoiceForm.zipCode"
            :maxlength="6"
            placeholder="请填写邮政编码"
          />
        </el-form-item>
        <el-form-item label="联系邮箱" prop="email">
          <el-input v-model="invoiceForm.email" placeholder="请填写联系邮箱" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phoneNumber">
          <el-input
            v-model="invoiceForm.phoneNumber"
            :maxlength="11"
            placeholder="请填写联系电话"
          />
        </el-form-item>
        <el-form-item label="选择电子发票" prop="whetherElectronicInvoice">
          <el-radio-group v-model="invoiceForm.whetherElectronicInvoice">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
          <div>电子发票将通过邮件发送至你填写的邮箱</div>
        </el-form-item>
      </el-form>
      <div class="centent_bottom">
        <el-button type="primary" @click="handleSubmit(invoiceRef)"> 确定 </el-button>
        <el-button @click="invoiceShow = false"> 取消 </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, watch, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance } from 'element-plus';
import {
  itemList,
  invoiceApply,
  contractAdd,
  queryInvoiceConfig,
} from "@/api/control/order";

const props = defineProps({
  // 是否显示
  show: {
    type: Boolean,
    default: false,
  },
  // 操作
  action: {
    type: String,
    default: "",
  },
});

const emits = defineEmits(["update:show"]);
const dialogVisible = computed(() => props.show); // 控制弹窗显示
const orderList = ref<any>([]); // 订单列表
const ids = ref<any>([]); // 已选数据ID
const total = ref(); // 总条数
const multipleSelection = ref<any>([]); // 多选
const queryParams = ref<any>({
  sn: null,
  shoppingCarEnums: "CLOUD_SERVER",
  invoicing: 2,
  orderStatus: "SUCCESS",
  params: {
    pageNum: 1,
    pageSize: 10,
  },
});
const typeList = ref<any>([
  { value: "CLOUD_SERVER", label: "云服务器" },
  { value: "CLOUD_MARKET", label: "云市场" },
  { value: "GOV_CLOUD", label: "政务云" },
]);

const invoiceShow = ref(false); // 申请表单弹窗
const invoiceRef = ref();
const invoiceForm = ref<any>({
  invoiceType: 1, // 发票类型
  invoiceTittle: null, // 发票抬头（公司名称）
  taxpayerId: null, // 纳税人识别号
  recipientName: null, // 收件人姓名
  recipientAddress: null, // 收件人地址
  zipCode: null, // 邮政编码
  email: null, // 联系邮箱
  phoneNumber: null, // 联系电话
  whetherElectronicInvoice: true, // 是否选择电子发票
});
const invoiceRules = ref<any>({
  // 验证规则
  invoiceType: [{ required: true, message: "请选择发票类型", trigger: "change" }],
  invoiceTittle: [{ required: true, message: "请输入发票抬头", trigger: "blur" }],
  taxpayerId: [{ required: true, message: "请输入纳税人识别号", trigger: "blur" }],
  recipientName: [{ required: true, message: "请输入收件人姓名", trigger: "blur" }],
  recipientAddress: [{ required: true, message: "请输入收件人地址", trigger: "blur" }],
  zipCode: [
    { required: true, message: "请输入邮政编码", trigger: "blur" },
    {
      pattern: /^[0-9]{6}$/,
      message: "必须是6位数字",
      trigger: "change",
    },
  ],
  email: [
    { required: true, message: "请输入联系邮箱", trigger: "blur" },
    {
      pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/,
      message: "必须是正确的邮箱格式",
      trigger: "change",
    },
  ],
  phoneNumber: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9])\d{8}$/,
      message: "必须是正确的手机号格式",
      trigger: "change",
    },
  ],
  whetherElectronicInvoice: [
    { required: true, message: "请选择是否选择电子发票", trigger: "change" },
  ],
});

watch(props, (val) => {
  if (val.action == "invoice") {
    queryParams.value.invoicing = 2;
    queryParams.value.contractStatus = null;
  } else {
    queryParams.value.contractStatus = 2;
    queryParams.value.invoicing = null;
  }
  getOrderList();
});

// 关闭弹窗
const closeDialog = () => {
  emits("update:show", false);
};

// 获取类型中文名称
const getEnumsLabel = (val: any) => {
  let row = typeList.value.find((i: any) => i.value == val);
  return row ? row.label : "";
};

// 获取订单列表
const getOrderList = () => {
  itemList(queryParams.value).then((res: any) => {
    orderList.value = res.rows;
    total.value = res.total;
  });
};

// 设置不可选中
const selectable = (row: any) => {
  if (props.action == "invoice") {
    return row.invoicing == 0;
  } else {
    return row.contractStatus == 0;
  }
};

// 搜索
const querySearch = () => {
  queryParams.value.params.pageNum = 1;
  getOrderList();
};

// 多选
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

// 重置
const resetQuery = () => {
  queryParams.value.sn = null;
  queryParams.value.shoppingCarEnums = "CLOUD_SERVER";
  queryParams.value.params.pageNum = 1;
  getOrderList();
};

// 提交申请开票/合同
const onSubmit = (row?: any) => {
  if (row) {
    ids.value = [row.orderItemId];
  } else {
    ids.value = multipleSelection.value.map((item: any) => item.orderItemId);
  }
  if (props.action == "invoice") {
    resetInvoice();
    queryInvoiceConfig().then((res: any) => {
      if (res.data) {
        Object.keys(invoiceForm.value)?.forEach((i) => {
          invoiceForm.value[i] = res.data[i];
        });
      }
      invoiceShow.value = true;
    });
  } else {
    ElMessageBox.confirm("确认申请已选择的" + ids.value.length + "条合同吗?", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        let data = {
          orderItemIds: ids.value,
        };
        contractAdd(data).then(() => {
          ElMessage.success("申请已提交");
          getOrderList();
        });
      })
      .catch(() => {});
  }
};

// 提交申请开票
const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm(
        "确认为已选择的" + ids.value.length + "条订单申请开票吗?",
        "提示",
        {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          let data = {
            orderItemId: ids.value.toString(),
            sysUserInvoiceInformation: invoiceForm.value,
          };
          invoiceApply(data).then(() => {
            ElMessage.success("申请已提交");
            invoiceShow.value = false;
            getOrderList();
          });
        })
        .catch(() => {});
    }
  });
};

// 重置表单
const resetInvoice = () => {
  invoiceForm.value = {
    invoiceType: 1, // 发票类型
    invoiceTittle: null, // 发票抬头（公司名称）
    taxpayerId: null, // 纳税人识别号
    recipientName: null, // 收件人姓名
    recipientAddress: null, // 收件人地址
    zipCode: null, // 邮政编码
    email: null, // 联系邮箱
    phoneNumber: null, // 联系电话
    whetherElectronicInvoice: true, // 是否选择电子发票
  };
};
</script>
<style lang="less" scoped>
.query {
  width: 100%;
  height: 50px;
  margin: 20px 0;
  display: flex;
}
.page-footer {
  display: flex;
  justify-content: flex-end;
  margin: 20px 0;
}
</style>
<style>
.title-style {
  height: 60px;
  background-color: #f6faff !important;
}
</style>
